package com.smomo.blog.config.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域过滤器
 * @author
 * @date
 * @apiNote
 */
@Component
public class MyCorsFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        //指定允许其他域名访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        //是否允许后续请求携带认证信息（cookies），该值只能是true,否则不返回
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //允许其他请求类型
        response.setHeader("Access-Control-Allow-Methods", "*");
        //允许的请求头字段
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,Authorization");
        //响应报头公开，可以指定，这里默认全部公开
        response.setHeader("Access-Control-Expose-Headers", "*");
        //用来指定本次预检请求的有效期，单位为秒，，在此期间不用发出另一条预检请求
        response.setHeader("Access-Control-Max-Age", "3600");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}
